<script lang="ts" setup>
import { onMounted, reactive, ref, VueElement, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { MenuProps, ItemType } from "ant-design-vue";
import { MenuType } from "../Menu/Menu";
import {
  MenuFoldOutlined
} from "@ant-design/icons-vue"

const props = defineProps({
  productMenuList: {
    type: Array,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
});

const selectedKeys = ref<string[]>(["softwareCenter"]);
const openKeys = ref<string[]>(["sub1"]);
const router = useRouter();
const route = useRoute();

const items = reactive<ItemType[]>([
  getItem(
    "",
    "grp",
    null,
    (props.productMenuList as MenuType[])
      .filter((val) => !val.hidden)
      .map((val) => getItem(val.label, val.name)),
    "group"
  ),
]);

const updateMenu = () => {
  const base = location.hash.replace("#/", "").replace(/\?.*/, '');

  if (base.indexOf("/") === -1) {
    selectedKeys.value[0] = (props.productMenuList as MenuType[])[0].name;
    return;
  }

  let route: string[] = [];
  const arr = base.split("/");
  route = arr.reverse();

  const menuItem = (props.productMenuList as MenuType[]).find((val) => {
    return val.name === route[0];
  });

  if (menuItem)
    selectedKeys.value[0] = menuItem.hidden?.alias
      ? menuItem.hidden.alias
      : menuItem.name;
};

watch(() => route.path, () => {
  updateMenu()
})

onMounted(() => {
  updateMenu();
});


function getItem(
  label: VueElement | string,
  key: string,
  icon?: any,
  children?: ItemType[],
  type?: "group"
): ItemType {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as ItemType;
}

const handleClick: MenuProps["onClick"] = (e) => {
  router.push({
    path: `/${props.name}/${e.key}`,
  });
};

const open = ref<boolean>(false);


const showDrawer = () => {
  open.value = true;
};

</script>

<template>
  <a-button type="primary" class="flex justify-center items-center fixed top-1/10 right-0 z-99 md:hidden"
    @click="showDrawer">
    <MenuFoldOutlined />
  </a-button>
  <a-drawer v-model:open="open" :bodyStyle="{ padding: 0 }" placement="right">
    <a-menu id="dddddd" v-model:openKeys="openKeys" v-model:selectedKeys="selectedKeys" style="width: 100%"
      mode="inline" :items="items" @click="handleClick"></a-menu>
  </a-drawer>
  <a-menu id="dddddd" v-model:openKeys="openKeys" v-model:selectedKeys="selectedKeys" style="width: 256px" mode="inline"
    class="hidden md:block" :items="items" @click="handleClick"></a-menu>
</template>
